package com.ebupt.migu.music.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.schedule.mapper.RedisTaskMapper;
import com.ebupt.migu.music.schedule.service.RedisTaskService;
import com.ebupt.migu.music.userGroup.entity.ActiveArrayBean;
import com.ebupt.migu.music.userGroup.entity.AttributeBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Intellij IDEA.
 * User:  liuyangyang@cd.ebupt.com
 * Date:  2020/3/17
 */
@Slf4j
@Service
public class RedisTaskServiceImpl implements RedisTaskService {

    @Autowired
    private RedisTaskMapper redisTaskMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void cleanRedis() {
        // 查询用户群列表
        // create_status in (8,9)
        // 8-已失效（锁定状态）；9-已删除；
        List<String> gids = redisTaskMapper.queryGids();
        if (null != gids && gids.size() != 0) {
            log.info("失效和已经被删除的人群共计：{}个", gids.size());
            // 删除redis key
            for (String gid : gids) {
                redisTemplate.delete(gid);
                redisTemplate.delete(gid + "-uid");
                redisTemplate.delete(gid + "-imei");
                redisTemplate.delete(gid + "-phone");
                redisTemplate.delete(gid + "-push-imei");
                // 将人群规模，号码用户规模，客户端规模修改为0
                redisTaskMapper.updateUserGroupInfo(gid);
            }
        }
    }

    /**
     * 扫描Redis中的key，更新数据库中的人群规模
     * 用户群创建方式：
     * 1-静态条件创建；2-动态条件创建；3-文件导入创建；4-交集创建；5-并集创建；6-左差集创建；7-右差集创建；8-对称差集创建；9-ftp同步
     * 用户群状态：
     * 1-创建中；2-待提交（草稿箱）；3-待更新；4-更新中；5-已完成；6-提取失败；7-导入失败；8-已失效（锁定状态）；9-已删除；10-执行sql失败;
     */
    @Override
    public void updateUserGroupSize() {
        // 查询符合条件的用户群
        List<HashMap<String, String>> groups = redisTaskMapper.queryGroups();
        for (HashMap<String, String> group : groups) {
            String groupId = group.get("groupId");
            int createWay = Integer.getInteger(group.get("createWay"));
            // 动态标签创建的人群且为DPI人群
            if (createWay == 2 && isDyna(group.get("groupAttribute"))) {
                // 不存在key或者key元素为空
                if (!redisTemplate.hasKey(groupId + "-phone") || redisTemplate.opsForSet().size(groupId + "-phone") == 0) {
                    redisTaskMapper.updateUserGroupSize(groupId);
                    redisTaskMapper.updateMobileUser(groupId);
                }
                continue;
            } else {
                if (!redisTemplate.hasKey(groupId + "-phone") || redisTemplate.opsForSet().size(groupId + "-phone") == 0) {
                    redisTaskMapper.updateMobileUser(groupId);
                }
                if (!redisTemplate.hasKey(groupId + "-uid") || redisTemplate.opsForSet().size(groupId + "-uid") == 0) {
                    redisTaskMapper.updateUserGroupSize(groupId);
                }
                if (!redisTemplate.hasKey(groupId + "-imei") || redisTemplate.opsForSet().size(groupId + "-imei") == 0) {
                    redisTaskMapper.updateClientUser(groupId);
                }
            }
        }
    }

    /**
     * 验证是否DPI人群
     *
     * @param json
     * @return
     */
    public boolean isDyna(String json) {
        //JSON转换成对应的JavaBean
        AttributeBean bean = JSON.parseObject(json, AttributeBean.class);
        // 来源平台页面选择
        // 1：咪咕音乐 2：DPI
        if (StringUtils.isNotBlank(bean.getUserRadio()) && "2".equals(bean.getUserRadio())) {
            return true;
        }
        return false;
    }

}
